<?php
if (!file_exists('../install.lock')) {
    exit('fail');
}

require_once 'config.php';
require_once 'alipay.php';

// 记录通知日志
function writeLog($message) {
    $log_file = __DIR__ . '/notify.log';
    $time = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$time] $message\n", FILE_APPEND | LOCK_EX);
}

writeLog('收到支付宝异步通知');

try {
    // 获取支付宝POST过来的通知信息
    $data = $_POST;
    
    if (empty($data)) {
        writeLog('通知数据为空');
        exit('fail');
    }
    
    writeLog('通知数据: ' . json_encode($data));
    
    // 验证签名
    $alipay = new AlipayF2F(
        ALIPAY_APP_ID,
        ALIPAY_PRIVATE_KEY,
        ALIPAY_PUBLIC_KEY,
        ALIPAY_NOTIFY_URL,
        ALIPAY_RETURN_URL
    );
    
    if (!$alipay->verifyNotify($data)) {
        writeLog('签名验证失败');
        exit('fail');
    }
    
    writeLog('签名验证成功');
    
    // 获取订单号
    $order_no = $data['out_trade_no'] ?? '';
    $trade_status = $data['trade_status'] ?? '';
    $total_amount = $data['total_amount'] ?? '';
    $trade_no = $data['trade_no'] ?? '';
    
    if (empty($order_no)) {
        writeLog('订单号为空');
        exit('fail');
    }
    
    writeLog("订单号: $order_no, 交易状态: $trade_status, 金额: $total_amount");
    
    // 查询订单
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE order_no = ?");
    $stmt->execute([$order_no]);
    $order = $stmt->fetch();
    
    if (!$order) {
        writeLog("订单不存在: $order_no");
        exit('fail');
    }
    
    // 检查订单状态
    if ($order['status'] === 'paid') {
        writeLog("订单已支付，忽略重复通知: $order_no");
        exit('success');
    }
    
    // 处理不同的交易状态
    switch ($trade_status) {
        case 'TRADE_SUCCESS':
            // 支付成功
            writeLog("支付成功，开始处理订单: $order_no");
            
            // 验证金额
            if (abs($order['total_amount'] - $total_amount) > 0.01) {
                writeLog("金额不匹配，订单金额: {$order['total_amount']}, 支付金额: $total_amount");
                exit('fail');
            }
            
            // 更新订单状态
            $stmt = $pdo->prepare("UPDATE orders SET status = 'paid', paid_at = NOW(), trade_no = ? WHERE order_no = ?");
            $stmt->execute([$trade_no, $order_no]);
            
            // 生成卡密并发送
            $result = generateAndSendKami($order);
            
            if ($result) {
                writeLog("卡密生成成功: $order_no");
            } else {
                writeLog("卡密生成失败: $order_no");
            }
            
            writeLog("订单处理完成: $order_no");
            exit('success');
            break;
            
        case 'TRADE_CLOSED':
            // 交易关闭
            writeLog("交易关闭: $order_no");
            $stmt = $pdo->prepare("UPDATE orders SET status = 'expired' WHERE order_no = ?");
            $stmt->execute([$order_no]);
            exit('success');
            break;
            
        case 'WAIT_BUYER_PAY':
            // 等待买家付款
            writeLog("等待买家付款: $order_no");
            exit('success');
            break;
            
        default:
            writeLog("未知交易状态: $trade_status");
            exit('success');
            break;
    }
    
} catch (Exception $e) {
    writeLog('处理异常: ' . $e->getMessage());
    exit('fail');
}

/**
 * 生成卡密并发送
 */
function generateAndSendKami($order) {
    global $pdo;
    
    try {
        // 获取商品信息
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$order['product_id']]);
        $product = $stmt->fetch();
        
        if (!$product) {
            writeLog("商品不存在: {$order['product_id']}");
            return false;
        }
        
        // 生成卡密
        $kami_list = [];
        for ($i = 0; $i < $order['quantity']; $i++) {
            $kami_key = generateKamiKey();
            
            // 计算过期时间
            $expire_time = null;
            if ($product['duration_type'] && $product['duration_value'] > 0) {
                switch ($product['duration_type']) {
                    case 'minute':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} minutes"));
                        break;
                    case 'hour':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} hours"));
                        break;
                    case 'day':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} days"));
                        break;
                    case 'week':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} weeks"));
                        break;
                    case 'month':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} months"));
                        break;
                    case 'year':
                        $expire_time = date('Y-m-d H:i:s', strtotime("+{$product['duration_value']} years"));
                        break;
                }
            }
            
            // 插入卡密
            $stmt = $pdo->prepare("INSERT INTO kami (kami_key, expire_time, max_uses, created_by, type, order_no) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $kami_key,
                $expire_time,
                0, // 无限制使用次数
                'system', // 系统生成
                $product['name'],
                $order['order_no']
            ]);
            
            $kami_list[] = $kami_key;
        }
        
        // 更新订单的卡密信息
        $kami_text = implode("\n", $kami_list);
        $stmt = $pdo->prepare("UPDATE orders SET kami_list = ? WHERE order_no = ?");
        $stmt->execute([$kami_text, $order['order_no']]);
        
        writeLog("生成卡密成功，数量: " . count($kami_list));
        return true;
        
    } catch (Exception $e) {
        writeLog("生成卡密失败: " . $e->getMessage());
        return false;
    }
}
?> 